package com.example.basic.rabbit.producer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author root
 * @date 2021-03-06 11:15
 */
public class TTLProducer {

    private static final String EXCHANGE_DLX_NAME = "exchange.dlx2";
    private static final String EXCHANGE_NAME_1 = "exchange.normal2";
    private static final String TYPE = "direct";
    private static final String ROUTING_KEY = "routingkey";
    private static final String QUEUE_NAME = "queue.normal2";
    private static final String QUEUE_DLX_NAME = "queue.dlx2";
    private static final String IP_ADDRESS = "192.168.142.131";
    private static final int PORT = 5672;


    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(IP_ADDRESS);
        factory.setPort(PORT);
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setVirtualHost("my_vhost");
        Connection connection = factory.newConnection();  // 创建链接
        Channel channel = connection.createChannel();     // 创建信道

        // 创建一个持久化、非拍他、非自动删除的交换器
        channel.exchangeDeclare(EXCHANGE_NAME_1, "fanout", true);
        Map<String, Object> argus = new HashMap<>();
        // 设置超时时间
        argus.put("x-message-ttl", 10000);
        // 设置死信队列  超时时间到期后 信息到达死信队列 消费者订阅死信队列
        argus.put("x-dead-letter-exchange", EXCHANGE_DLX_NAME);
        argus.put("x-dead-letter-routing-key", ROUTING_KEY);
        channel.queueDeclare(QUEUE_NAME,true, false, false, argus);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME_1, "");

        // 创建死信队列
        channel.exchangeDeclare(EXCHANGE_DLX_NAME, "direct", true);
        channel.queueDeclare(QUEUE_DLX_NAME, true, false, false, null);
        channel.queueBind(QUEUE_DLX_NAME, EXCHANGE_DLX_NAME, ROUTING_KEY);

        channel.basicPublish(EXCHANGE_NAME_1, "rk",
                MessageProperties.PERSISTENT_TEXT_PLAIN, "dlx".getBytes());

        // 关闭资源
        channel.close();
        connection.close();
    }
}
